﻿using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.ServiceModel.Web;
using SocialShare.DataAccessLayer;
using SocialShare.BusinessEntities;
using SocialShare.DAL.Facades;
using System.ServiceModel.Activation;
using System.IO;
using System.Configuration;
using SocialShare.BLL;
using System.Xml;
using System.Web;

namespace SocialShare.Web.Services
{
    [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SocialShare_Service : DataService<SocialShareDatabaseContext>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.UseVerboseErrors = true;
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<BlogPost> GetRecentBlogs()
        {
            BlogFacade facade = new BlogFacade();
            List<BlogPost> posts= facade.GetRecentBlogs();
            

            return posts;
        }

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<SocialShare_Members> GetAllMembers()
        {
            MemberFacade facade = new MemberFacade();
            return facade.GetAllMembers();
        }

       
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public Int32 GetAllCmsCount()
        {
            SiteContentFacade facade = new SiteContentFacade();
            return facade.GetAllSiteContents().Count;
        }

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<BlogPost> GetAllBlog(String sortOrder = default(String), Int32 startRowIndex = default(Int32), Int32 maximumRows = default(Int32))
        {
            BlogFacade facade = new BlogFacade();
            List<BlogPost> posts = facade.GetAllBlogPosts(sortOrder, startRowIndex, maximumRows);
            return posts;
        }

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<SocialShareConfigMessages> GetAllConfigSettings()
        {
            List<SocialShareConfigMessages> configList = new List<SocialShareConfigMessages>();
            String filePath =HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()]);
            FileInfo fInfo = new FileInfo(filePath);
            String configValue = String.Empty;
            if (fInfo.Exists)
            {
                XmlDocument doc = new XmlDocument();

                doc.Load(fInfo.FullName);
                XmlNodeList list = doc.GetElementsByTagName("CONFIGURATIONS");
                if (list != null && list.Count > 0)
                {
                    foreach (XmlNode node in list)
                    {
                        XmlNodeList msglist = node.ChildNodes;
                        foreach (XmlNode childNode in msglist)
                        {
                            SocialShareConfigMessages message = new SocialShareConfigMessages();
                            message.Caption = childNode.Name;
                            message.Message = childNode.InnerText.Replace("'", "&quot;");
                            configList.Add(message);
                        }
                    }
                }
            }

            return configList;
        }

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        public List<SocialShareConfigMessages> GetAllMessages()
        {
            List<SocialShareConfigMessages> configList = new List<SocialShareConfigMessages>();
            String filePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()]);
            FileInfo fInfo = new FileInfo(filePath);
            String configValue = String.Empty;
            if (fInfo.Exists)
            {
                XmlDocument doc = new XmlDocument();

                doc.Load(fInfo.FullName);
                XmlNodeList list = doc.GetElementsByTagName("CONFIGURATIONS");
                if (list != null && list.Count > 0)
                {
                    foreach (XmlNode node in list)
                    {                      
                        XmlNodeList msglist = node.ChildNodes;
                        foreach (XmlNode childNode in msglist)
                        {
                            SocialShareConfigMessages message = new SocialShareConfigMessages();
                            message.Caption = childNode.Name;
                            message.Message = childNode.InnerText.Replace("'", "&quot;");
                            configList.Add(message);
                        }
                        
                    }
                }
            }

            return configList;
        }

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
        public Boolean UpdateAllSiteSettings()
        {
             Dictionary<String, String> dicMessages = new Dictionary<String, String>();            
            String[] strMsgArray = HttpContext.Current.Request.Cookies["_MESSAGES_TO_UPDATE"].Value.Split(new char[]{ ','});
            foreach (String strMsg in strMsgArray)
            {
                String[] strMsgValArray = strMsg.Split(new char[] { ':' });
                if (strMsgValArray.Length == 2)
                {
                    dicMessages.Add(strMsgValArray[0], strMsgValArray[1]);
                }
            }

            String filePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.SiteConfigLocation.ToString()]);
            FileInfo fInfo = new FileInfo(filePath);
            try
            {
                if (fInfo.Exists)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(fInfo.FullName);
                    XmlNodeList list = doc.GetElementsByTagName("CONFIGURATIONS");
                    if (list != null && list.Count > 0)
                    {
                        foreach (XmlNode node in list)
                        {
                            XmlNodeList msglist = node.ChildNodes;
                            foreach (XmlNode childNode in msglist)
                            {
                                childNode.InnerText=dicMessages[childNode.Name];                          
                                
                            }
                            doc.Save(fInfo.FullName);   
                        }
                    }

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
     

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped)]
        public Boolean UpdateAllMessages()
        {
            Dictionary<String, String> dicMessages = new Dictionary<String, String>();            
            String[] strMsgArray = HttpContext.Current.Request.Cookies["_MESSAGES_TO_UPDATE"].Value.Split(new char[]{ ','});
            foreach (String strMsg in strMsgArray)
            {
                String[] strMsgValArray = strMsg.Split(new char[] { ':' });
                if (strMsgValArray.Length == 2)
                {
                    dicMessages.Add(strMsgValArray[0], strMsgValArray[1]);
                }
            }

            String filePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings[APP_SETTINGS_NAME.MessageLocation.ToString()]);
            FileInfo fInfo = new FileInfo(filePath);
            try
            {
                if (fInfo.Exists)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(fInfo.FullName);
                    XmlNodeList list = doc.GetElementsByTagName("CONFIGURATIONS");
                    if (list != null && list.Count > 0)
                    {
                        foreach (XmlNode node in list)
                        {
                            XmlNodeList msglist = node.ChildNodes;
                            foreach (XmlNode childNode in msglist)
                            {
                                childNode.InnerText=dicMessages[childNode.Name];                          
                                
                            }
                            doc.Save(fInfo.FullName);   
                        }
                    }

                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
    }

}
